package com.yzt.zhuju;

import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.gu.toolargetool.TooLargeTool;
import com.yzt.zhuju.base.BaseApplication;
import com.yzt.zhuju.config.AppConfig;
import com.yzt.zhuju.config.AppConfigCacheManager;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.im.RongYunLoginEvent;
import com.yzt.zhuju.utils.ActivityManagerUtils;
import com.yzt.zhuju.utils.PreferencesUtils;
import com.yzt.zhuju.utils.SDKInitManager;
import com.yzt.zhuju.utils.SystemUtil;
import com.yzt.zhuju.utils.Utils;
import com.yzt.index.KeepAliveService;
import com.yzt.message.IMManager;
import com.yzt.p_base.utils.AppInfoUtils;
import com.yzt.p_base.utils.SharedPreferenceUtil;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import cn.jiguang.api.utils.JCollectionAuth;
import cn.jiguang.verifysdk.api.JVerificationInterface;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.functions.Consumer;
import io.reactivex.plugins.RxJavaPlugins;

/**
 * author : bob
 * date   : 2022/11/28
 * desc   : nomi 启动
 */
public class NomiApplication extends BaseApplication implements Application.ActivityLifecycleCallbacks,
        SDKInitManager.SDKInitCallBack {

    private static final String TAG = "NomiApplication";

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        Log.e(TAG, "onTrimMemory" + level);
        if (level == TRIM_MEMORY_UI_HIDDEN) {
            ImageLoadUtil.clearMemory(this);
        }
        ImageLoadUtil.trimMemory(this, level);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        TooLargeTool.startLogging(this);
        SharedPreferenceUtil.init(this);
        //  ARouter.getInstance().navigation(ICallService.class).preInitCall(this);

        /*
         * 以上部分在所有进程中会执行
         */
        if (!SystemUtil.inMainProcess(this)) {
            return;
        }

        AppConfigCacheManager.getInstance().setContext(this);
        SDKInitManager.callBack = this;
        registerActivityLifecycleCallbacks(this);

        if (SystemUtil.inMainProcess(AppConfig.application)) {
            //设置sdk init 回调，当首次安装并点击 同意用户协议的情况下，callback 将通知融云sdk 初始化
            SDKInitManager.initAll(this);
        }

        // 微信支付注册
        WXAPIFactory.createWXAPI(Utils.getApp(), "wx4b6080cc0837f2ec", true)
                .registerApp("wx4b6080cc0837f2ec");

        // 极光推送
        JPushInterface.init(Utils.getApp());
        JPushInterface.setDebugMode(BuildConfig.DEBUG);
        JCollectionAuth.setAuth(Utils.getApp(), true);
        // 极光一键登录
        JVerificationInterface.setDebugMode(BuildConfig.DEBUG);
        JVerificationInterface.init(Utils.getApp(), (code, msg) -> Log.e("tag", "JVerificationInterface code = " + code + " msg = " + msg));
    }

    private static void init(Application context) {

        //融云
        IMManager.getInstance().init(AppConfig.application);
        RxBus.getDefault().observerRxBus(RongYunLoginEvent.class, yunLoginEvent ->
                IMManager.getInstance().cacheConnectIM()
        );

        try {
            String processName = SystemUtil.getProcessNamePure(context);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                if (!AppInfoUtils.getAppPackageName().equals(processName)) {
                    WebView.setDataDirectorySuffix(processName);
                }
            }
//            if (AppInfoUtils.getAppPackageName().equals(processName)) {
//                Album.initialize(AlbumConfig.newBuilder(context)
//                        .setAlbumLoader(new MediaLoader())
//                        .setLocale(Locale.getDefault())
//                        .build()
//                );
//            }
        } catch (Exception ignored) {

        }

        RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {
                throwable.printStackTrace();//这里处理所有的Rxjava异常
            }
        });
    }

    @Override
    public void RYunInit(Application application) {
        AppConfigCacheManager.getInstance().setContext(application);
        init(application);
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {
        if (foregroundCount <= 0) {
            if (KeepAliveService.serviceIsLive) {
                try {
                    KeepAliveService.stopKeepAliveService(activity);
                } catch (Exception ignored) {

                }
            }
            if (RXingUtils.isLogin()) {
                Log.i(TAG, "从后台恢复到前台");
                Log.e(TAG, PreferencesUtils.getLastMsgStatus() + "");
            }
        }

        foregroundCount++;
    }

    @Override
    public void onActivityResumed(Activity activity) {
        ActivityManagerUtils.getInstance().setActivity(activity);
    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onActivityStopped(Activity activity) {
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {

    }

    /**
     * 对账号体系进行注册推送
     */
    public static void registerUserPush() {
        if (!RXingUtils.isLogin())
            return;
        Log.e("PushMessageReceiver", "[registerUserPush] " + "id" + RXingUtils.getUserId());
        // 极光推送设置别名
       // if (App.user != null) {
          //  JPushInterface.setAlias(Utils.getApp(), 1, "id" + App.user.getId());
       // }
    }

    /**
     * 关闭用户推送
     */
    public static void stopPush() {
//        if (App.user != null) {
//            JPushInterface.deleteAlias(Utils.getApp(), 1);
//        }
    }
}
